<template>
	<view class="pb-180">
		<image src="/static/dingbu.png" class="mine-navbar-bg" :style="{ height: navbarHeight + 'rpx' }"
			mode="aspectFill"></image>
		<u-navbar title="快检任务下发" :autoBack="true" leftIconColor="#fff" bgColor="transparent"
			:titleStyle="{ color: '#fff' }" safeAreaInsetTop placeholder>
		</u-navbar>
		<!-- 基本信息 -->
		<view class="w-710 mt-20 bgff pl-32 pr-32 br-20 mgt pt-20 pb-20">
			<view class="">基本信息</view>
			<view class="rowsb rowsm h-100 bor-b" @tap="!readonly && (showEduPicker = true)">
				<view>年份</view>
				<view class="trt fs-28 col999 rowsc rowsm" v-if="!form.detectionYear">请选择
					<u-icon v-if="!readonly" name="arrow-right" size="17" color="#999" style="vertical-align: top;"></u-icon>
				</view>
				<view class="trt fs-28" v-else>{{ form.detectionYear }}</view>
			</view>
			<view class="rowsb rowsm h-100 bor-b" @tap="!readonly && (showFastDetectionTypePicker = true)">
				<view>快检检测类别</view>
				<view class="trt fs-28 col999 rowsc rowsm" v-if="!form.fastDetectionType">请选择
					<u-icon v-if="!readonly" name="arrow-right" size="17" color="#999" style="vertical-align: top;"></u-icon>
				</view>
				<view class="trt fs-28" v-else>{{ getFastDetectionTypeLabel(form.fastDetectionType) }}</view>
			</view>
			<view class="rowsb rowsm h-100 bor-b" @tap="showFastDetectionAccordingPicker = true">
				<view>快速检测依据</view>
				<view class="trt fs-28 col999 rowsc rowsm" v-if="!form.fastDetectionAccording">请选择
					<u-icon name="arrow-right" size="17" color="#999" style="vertical-align: top;"></u-icon>
				</view>
				<view class="trt fs-28" v-else>{{ getFastDetectionAccordingLabel(form.fastDetectionAccording) }}</view>
			</view>
		</view>
		<!-- 执行机构信息 -->
		<view class="w-710 mt-20 bgff pl-32 pr-32 br-20 mgt pt-20 pb-20">
			<view class="">执行机构信息</view>
			<view class="rowsb rowsm h-100 bor-b" @tap="showInstitutionPicker = true">
				<view>检测机构</view>
				<view class="trt fs-28 col999 rowsc rowsm" v-if="!form.institutionName">请选择
					<u-icon name="arrow-right" size="17" color="#999" style="vertical-align: top;"></u-icon>
				</view>
				<view class="trt fs-28" v-else>{{ getInstitutionLabel(form.institutionName) }}</view>
			</view>
			<view class="rowsb rowsm h-100 bor-b" @tap="showInspectorPicker = true">
				<view>园区</view>
				<view class="trt fs-28 col999 rowsc rowsm" v-if="!form.orchardId">请选择
					<u-icon name="arrow-right" size="17" color="#999" style="vertical-align: top;"></u-icon>
				</view>
				<view class="trt fs-28" v-else>{{ getInspectorLabel(form.orchardId) }}</view>
			</view>
			<view class="rowsb rowsm h-100 bor-b" @tap="handleFastDetectionProjectPicker()">
				<view>快速检测项目</view>
				<view class="trt fs-28 col999 rowsc rowsm" v-if="!form.fastDetectionProject">请选择
					<u-icon name="arrow-right" size="17" color="#999" style="vertical-align: top;"></u-icon>
				</view>
				<view class="trt fs-28" v-else>{{ getFastDetectionProjectLabel(form.fastDetectionProject) }}</view>
			</view>
		</view>
		<!-- 样品明细 -->
		<view class="w-710 mt-20 bgff pl-32 pr-32 br-20 mgt pt-20 pb-20">
			<view class="fs-28 fw-b mb-20">样品明细</view>

			<!-- 样品列表 -->
			<view v-for="(sample, index) in form.sylFastSampleInfoList" :key="index" class="sample-card mb-20">
				<view class="sample-header">
					<view class="fs-26 fw-b col-green">{{ index + 1 }}号样品</view>
					<view class="fs-24 col-red" v-if="!isFromTask" @tap="handleDeleteSample(index)">删除</view>
				</view>

				<view class="sample-content">
					<!-- 产品名称 -->
					<view class="rowsb rowsm h-100 bor-b" @tap="handleSpeciesPicker(index)">
						<view>产品名称</view>
						<view class="trt fs-28 col999 rowsc rowsm" v-if="!sample.product">请选择
							<u-icon name="arrow-right" size="17" color="#999" style="vertical-align: top;"></u-icon>
						</view>
						<view class="trt fs-28" v-else>{{ sample.product }}</view>
					</view>

					<!-- 检测项目 -->
					<view class="rowsb rowsm h-100 bor-b" @tap="handleFastDetectionProjectPicker(index)">
						<view>检测项目</view>
						<view class="trt fs-28 col999 rowsc rowsm" v-if="!sample.detectionProject">请选择
							<u-icon name="arrow-right" size="17" color="#999" style="vertical-align: top;"></u-icon>
						</view>
						<view class="trt fs-28" v-else>{{ getFastDetectionProjectLabel(sample.detectionProject) }}
						</view>
					</view>

					<!-- 样品基数 -->
					<view class="rowsb rowsm h-100 bor-b">
						<view>样品基数</view>
						<input class="trt fs-28" placeholder="例:1kg/10kg,表示10kg中采样1kg"
							v-model="sample.cardinalNumber" :disabled="readonly" />
					</view>

					<!-- 样品来源 -->
					<view class="rowsb rowsm h-100 bor-b">
						<view>样品来源</view>
						<input class="trt fs-28" placeholder="请填写样品来源" v-model="sample.source" :disabled="readonly" />
					</view>

					<!-- 实验室编码 - 只有从待办任务跳转时显示 -->
					<view class="rowsb rowsm h-100 bor-b" v-if="isFromTask">
						<view>实验室编码</view>
						<input class="trt fs-28" placeholder="请填写实验室编码" v-model="sample.laboratoryCode" 
							:disabled="readonly || taskType === 'sampling'" />
					</view>

					<!-- 抽样单图片 - 只有从抽样单跳转时显示 -->
					<view class="rowsb rowsm h-100 bor-b" v-if="isFromTask && taskType === 'sampling'">
						<view>抽样单图片</view>
						<view class="trt fs-28 col999 rowsc rowsm" v-if="!sample.sampleImgUrl">请上传
							<u-icon name="arrow-right" size="17" color="#999" style="vertical-align: top;"></u-icon>
						</view>
						<view class="trt fs-28" v-else>已上传</view>
					</view>

					<!-- 检测单图片 - 只有从检测单跳转时显示 -->
					<view class="rowsb rowsm h-100 bor-b" v-if="isFromTask && taskType === 'detection'">
						<view>检测单图片</view>
						<view class="trt fs-28 col999 rowsc rowsm" v-if="!sample.detectionImgUrl">请上传
							<u-icon name="arrow-right" size="17" color="#999" style="vertical-align: top;"></u-icon>
						</view>
						<view class="trt fs-28" v-else>已上传</view>
					</view>

					<!-- 抽样单描述 - 只有从抽样单跳转时显示 -->
					<view class="rowsb rowsm h-100 bor-b" v-if="isFromTask && taskType === 'sampling'">
						<view>抽样单描述</view>
						<input class="trt fs-28" placeholder="请填写抽样单描述" v-model="sample.sampleImgRemark" :disabled="readonly" />
					</view>

					<!-- 检测单描述 - 只有从检测单跳转时显示 -->
					<view class="rowsb rowsm h-100 bor-b" v-if="isFromTask && taskType === 'detection'">
						<view>检测单描述</view>
						<input class="trt fs-28" placeholder="请填写检测单描述" v-model="sample.detectionImgRemark" :disabled="readonly" />
					</view>

					<!-- 是否合格 - 只有从待办任务跳转时显示 -->
					<view class="rowsb rowsm h-100" v-if="isFromTask">
						<view>是否合格</view>
						<view class="trt fs-28 col999 rowsc rowsm" @tap="!readonly && handleQualifiedPicker(index)" 
							:class="{ 'disabled': readonly || taskType === 'sampling' }">
							<view v-if="sample.qualified === undefined || sample.qualified === null" class="rowsc rowsm">请选择
								<u-icon v-if="!readonly && taskType !== 'sampling'" name="arrow-right" size="17" color="#999" style="vertical-align: top;"></u-icon>
							</view>
							<view v-else>{{ sample.qualified ? '合格' : '不合格' }}</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 添加样品按钮 -->
			<view class="add-sample-btn" v-if="!isFromTask" @tap="handleAddSample">
				<view class="w-180 h-80 rowsc rowsm br-8 fs-28 colfff" style="background: #67C23A;">添加样品</view>
			</view>
		</view>
		<view class="w-690 h-88 br-16 fixed rowsa rowsm fs-36 colfff " style="bottom: 68rpx;left: 30rpx;"
			v-if="!isFromTask">
			<view class="w-200 bg rowsc rowsm colfff br-8" @click="submitDraft()">草稿</view>
			<view class="w-200 bg rowsc rowsm colfff br-8" @click="submitTask()">提交</view>
			<view class="w-200 bg rowsc rowsm colfff br-8" @click="resetForm()">重置</view>
		</view>
		
		<!-- 来自待办任务时的提交按钮 -->
		<view class="w-690 h-88 br-16 fixed rowsa rowsm fs-36 colfff " style="bottom: 68rpx;left: 30rpx;"
			v-if="isFromTask && !readonly">
			<view class="w-690 bg rowsc rowsm colfff br-8" @click="submitSampleInfo()">提交抽样信息</view>
		</view>
		<!-- 年份选择 -->
		<u-picker :show="showEduPicker" :columns="eduColumns" @confirm="yearConfirm" @cancel="showEduPicker = false"
			@close="showEduPicker = false" />
		<!-- 快速检测依据选择 -->
		<u-picker :show="showFastDetectionAccordingPicker" :columns="fastDetectionAccordingColumns"
			@confirm="fastDetectionAccordingConfirm" @cancel="showFastDetectionAccordingPicker = false"
			@close="showFastDetectionAccordingPicker = false" />
		<!-- 快检检测类别选择 -->
		<u-picker :show="showFastDetectionTypePicker" :columns="fastDetectionTypeColumns"
			@confirm="fastDetectionTypeConfirm" @cancel="showFastDetectionTypePicker = false"
			@close="showFastDetectionTypePicker = false" />
		<!-- 检测机构选择 -->
		<u-picker :show="showInstitutionPicker" :columns="institutionColumns" @confirm="institutionConfirm"
			@cancel="showInstitutionPicker = false" @close="showInstitutionPicker = false" />
		<!-- 园区选择 -->
		<u-picker :show="showInspectorPicker" :columns="inspectorColumns" @confirm="inspectorConfirm"
			@cancel="showInspectorPicker = false" @close="showInspectorPicker = false" />
		<!-- 快速检测项目选择 -->
		<u-picker :show="showFastDetectionProjectPicker" :columns="fastDetectionProjectColumns"
			@confirm="fastDetectionProjectConfirm" @cancel="showFastDetectionProjectPicker = false"
			@close="showFastDetectionProjectPicker = false" />
		<!-- 树种选择 -->
		<u-picker :show="showSpeciesPicker" :columns="speciesColumns" @confirm="speciesConfirm"
			@cancel="showSpeciesPicker = false" @close="showSpeciesPicker = false" />
		<!-- 是否合格选择 -->
		<u-picker :show="showQualifiedPicker" :columns="qualifiedColumns" @confirm="qualifiedConfirm"
			@cancel="showQualifiedPicker = false" @close="showQualifiedPicker = false" />
	</view>
</template>

<script>
import { listFastDetectionAccording, listInstitution, listFastDetectionType, listInspector, listFastDetectionTypeMei, listFastDetectionTypeJiao, listSpecies, addFastDetectionTask, batchUpdateSampleInfo } from '@/api/kuaijian'
export default {
	data() {
		return {
			form: {
				attachmentLink: null,
				createBy: null,
				createDeptId: null,
				createDeptName: null,
				createName: null,
				createTime: null,
				detectionYear: "",//年份
				executionAgency: null,
				fastDetectionAccording: "",//快速检测依据
				fastDetectionProject: "",//快速检测项目
				fastDetectionType: "",//快检检测类别
				id: null,
				instanceId: null,
				institutionId: null,//检测机构ID
				institutionName: "",//检测机构名称
				orchardId: null,//园区ID
				orchardName: null,//园区名称
				status: "2",
				sylFastSampleInfoList: [{ 
					product: "", 
					productId: null, 
					detectionProject: "", 
					cardinalNumber: "", 
					source: "", 
					sampleImgUrl: "",
					laboratoryCode: "",
					sampleImgRemark: "",
					qualified: null
				}],//样品明细
				updateTime: null,
				userId: null
			},
			showEduPicker: false,
			showFastDetectionAccordingPicker: false,
			showInstitutionPicker: false,
			showFastDetectionTypePicker: false,
			showInspectorPicker: false,
			eduColumns: [
				['2020', '2021', '2022', '2023', '2024', '2025'],
			],
			fastDetectionAccordingColumns: [],//快检检测依据
			fastDetectionAccordingData: [], // 保存原始数据
			fastDetectionTypeColumns: [],//快检检测类别
			fastDetectionTypeData: [], // 保存原始数据
			institutionColumns: [],//检测机构
			institutionData: [], // 保存原始数据
			inspectorColumns: [],//园区
			inspectorData: [], // 保存原始数据
			fastDetectionProjectColumns: [],//快速检测项目
			fastDetectionProjectData: [], // 保存原始数据
			showFastDetectionProjectPicker: false,
			speciesColumns: [],//树种
			speciesData: [], // 保存原始数据
			showSpeciesPicker: false,
			currentSampleIndex: 0, // 当前操作的样品索引
			isFromTask: false, // 是否来自待办任务
			taskType: '', // 任务类型：sampling(抽样单) 或 detection(检测单)
			readonly: false, // 是否只读模式
			showQualifiedPicker: false, // 是否合格选择器
			qualifiedColumns: [['合格', '不合格']], // 是否合格选项
		}
	},
	onLoad(options) {
		this.getFastDetectionAccordingList();
		this.getInstitutionList();
		this.getFastDetectionTypeList();
		this.getInspectorList();
		this.getSpeciesList();
		
		// 如果有传递的任务数据，进行回显
		if (options.taskData) {
			this.isFromTask = true; // 标记来自待办任务
			// 根据taskDefinitionKey判断任务类型
			if (options.taskType) {
				this.taskType = options.taskType;
			} else {
				// 默认根据taskDefinitionKey判断
				this.taskType = 'sampling'; // 默认为抽样单
			}
			// 检查是否只读模式
			if (options.readonly === 'true') {
				this.readonly = true;
			}
			try {
				const taskData = JSON.parse(decodeURIComponent(options.taskData));
				this.fillFormWithTaskData(taskData);
			} catch (error) {
				console.error('解析任务数据失败:', error);
			}
		}
	},
	methods: {
		// 根据任务数据回显表单
		fillFormWithTaskData(taskData) {
			console.log('回显任务数据:', taskData);
			console.log('样品明细数据:', taskData.sylFastSampleInfoList);
			
			// 基本信息回显
			if (taskData.detectionYear) {
				this.form.detectionYear = taskData.detectionYear;
			}
			if (taskData.fastDetectionType) {
				this.form.fastDetectionType = taskData.fastDetectionType;
			}
			if (taskData.fastDetectionAccording) {
				this.form.fastDetectionAccording = taskData.fastDetectionAccording;
			}
			if (taskData.institutionId) {
				this.form.institutionId = taskData.institutionId;
			}
			if (taskData.institutionName) {
				this.form.institutionName = taskData.institutionName;
			}
			if (taskData.orchardId) {
				this.form.orchardId = taskData.orchardId;
			}
			if (taskData.orchardName) {
				this.form.orchardName = taskData.orchardName;
			}
			if (taskData.fastDetectionProject) {
				this.form.fastDetectionProject = taskData.fastDetectionProject;
			}
			
			// 样品明细回显
			if (taskData.sylFastSampleInfoList && taskData.sylFastSampleInfoList.length > 0) {
				this.form.sylFastSampleInfoList = taskData.sylFastSampleInfoList.map(sample => ({
					id: sample.id, // 抽样ID
					product: sample.product || '',
					productId: sample.productId || null,
					detectionProject: sample.detectionProject || '',
					cardinalNumber: sample.cardinalNumber || '',
					source: sample.source || '',
					sampleImgUrl: sample.sampleImgUrl || '',
					laboratoryCode: sample.laboratoryCode || '',
					sampleImgRemark: sample.sampleImgRemark || '',
					detectionImgUrl: sample.detectionImgUrl || '',
					detectionImgRemark: sample.detectionImgRemark || '',
					qualified: sample.status === 1 ? true : sample.status === 2 ? false : null // 转换状态为布尔值
				}));
				console.log('转换后的样品数据:', this.form.sylFastSampleInfoList);
			}
			
			// 根据检测依据更新检测项目选项
			if (taskData.fastDetectionAccording) {
				this.updateFastDetectionProjectOptions();
			}
		},
		
		// 快检检测依据
		getFastDetectionAccordingList() {
			listFastDetectionAccording().then(res => {
				console.log('快检检测依据数据:', res);
				if (res.code === 200 && res.data) {
					// 将数据转换为picker需要的格式
					this.fastDetectionAccordingColumns = [res.data.map(item => item.dictLabel)];
					// 保存原始数据用于获取对应的值
					this.fastDetectionAccordingData = res.data;
					console.log('快检检测依据picker数据:', this.fastDetectionAccordingColumns);
				}
			});
		},
		// 快检检测类别
		getFastDetectionTypeList() {
			listFastDetectionType().then(res => {
				if (res.code === 200 && res.data) {
					// 将数据转换为picker需要的格式
					this.fastDetectionTypeColumns = [res.data.map(item => item.dictLabel)];
					// 保存原始数据用于获取对应的值
					this.fastDetectionTypeData = res.data;
				}
			});
		},
		// 检测机构
		getInstitutionList() {
			listInstitution().then(res => {
				if (res.code === 200 && res.rows) {
					// 将数据转换为picker需要的格式
					this.institutionColumns = [res.rows.map(item => item.organizationName)];
					// 保存原始数据用于获取对应的值
					this.institutionData = res.rows;
				}
			});
		},
		// 园区列表
		getInspectorList() {
			listInspector().then(res => {
				console.log('园区数据:', res);
				if (res.code === 200 && res.rows) {
					this.inspectorColumns = [res.rows.map(item => item.name)];
					this.inspectorData = res.rows;
					console.log('园区picker数据:', this.inspectorColumns);
				}
			});
		},
		// 树种列表
		getSpeciesList() {
			listSpecies().then(res => {
				console.log('树种数据:', res);
				if (res.code === 200 && res.rows) {
					this.speciesColumns = [res.rows.map(item => item.treeSpeciesName)];
					this.speciesData = res.rows;
					console.log('树种picker数据:', this.speciesColumns);
				}
			});
		},
		// 年份选择
		yearConfirm(e) {
			this.form.detectionYear = e.value[0];
			this.showEduPicker = false;
		},
		// 快速检测依据选择
		fastDetectionAccordingConfirm(e) {
			const selectedLabel = e.value[0];
			// 根据选中的标签找到对应的值
			const selectedItem = this.fastDetectionAccordingData.find(item => item.dictLabel === selectedLabel);
			if (selectedItem) {
				this.form.fastDetectionAccording = selectedItem.dictValue;
				// 根据检测依据更新检测项目选项
				this.updateFastDetectionProjectOptions();
			}
			this.showFastDetectionAccordingPicker = false;
		},
		// 检测机构选择
		institutionConfirm(e) {
			const selectedLabel = e.value[0];
			// 根据选中的标签找到对应的值
			const selectedItem = this.institutionData.find(item => item.organizationName === selectedLabel);
			if (selectedItem) {
				this.form.institutionId = selectedItem.id; // 设置institution_id
				this.form.institutionName = selectedItem.organizationName; // 设置institution_name
			}
			this.showInstitutionPicker = false;
		},
		// 快检检测类别选择
		fastDetectionTypeConfirm(e) {
			const selectedLabel = e.value[0];
			// 根据选中的标签找到对应的值
			const selectedItem = this.fastDetectionTypeData.find(item => item.dictLabel === selectedLabel);
			if (selectedItem) {
				this.form.fastDetectionType = selectedItem.dictValue;
			}
			this.showFastDetectionTypePicker = false;
		},
		// 根据值获取快检检测依据的标签
		getFastDetectionAccordingLabel(value) {
			const item = this.fastDetectionAccordingData.find(item => item.dictValue === value);
			return item ? item.dictLabel : value;
		},
		// 根据值获取快检检测类别的标签
		getFastDetectionTypeLabel(value) {
			const item = this.fastDetectionTypeData.find(item => item.dictValue === value);
			return item ? item.dictLabel : value;
		},
		// 园区选择
		inspectorConfirm(e) {
			const selectedLabel = e.value[0];
			// 根据选中的标签找到对应的值
			const selectedItem = this.inspectorData.find(item => item.name === selectedLabel);
			if (selectedItem) {
				this.form.orchardId = selectedItem.id; // 设置园区ID
				this.form.orchardName = selectedItem.name; // 设置园区名称
				// 清空所有样品的产品选择
				this.form.sylFastSampleInfoList.forEach(sample => {
					sample.product = '';
					sample.productId = null;
				});
			}
			this.showInspectorPicker = false;
		},
		// 根据值获取检测机构的标签
		getInstitutionLabel(value) {
			const item = this.institutionData.find(item => item.id === value);
			return item ? item.organizationName : value;
		},
		// 根据值获取园区的标签
		getInspectorLabel(value) {
			const item = this.inspectorData.find(item => item.id === value);
			return item ? item.name : value;
		},
		// 根据检测依据更新检测项目选项
		updateFastDetectionProjectOptions() {
			const detectionAccording = this.form.fastDetectionAccording;
			
			if (detectionAccording === '1') {
				// 当检测依据为1时，使用酶抑制率法检测项目
				this.getFastDetectionProjectMei();
			} else if (detectionAccording === '2') {
				// 当检测依据为2时，使用胶体金免疫层析法检测项目
				this.getFastDetectionProjectJiao();
			} else {
				// 默认清空选项
				this.fastDetectionProjectColumns = [];
				this.fastDetectionProjectData = [];
			}
		},
		// 获取酶抑制率法检测项目
		getFastDetectionProjectMei() {
			listFastDetectionTypeMei().then(res => {
				console.log('酶抑制率法检测项目数据:', res);
				if (res.code === 200 && res.data) {
					this.fastDetectionProjectColumns = [res.data.map(item => item.dictLabel)];
					this.fastDetectionProjectData = res.data;
					console.log('酶抑制率法检测项目picker数据:', this.fastDetectionProjectColumns);
				}
			});
		},
		// 获取胶体金免疫层析法检测项目
		getFastDetectionProjectJiao() {
			listFastDetectionTypeJiao().then(res => {
				console.log('胶体金免疫层析法检测项目数据:', res);
				if (res.code === 200 && res.data) {
					this.fastDetectionProjectColumns = [res.data.map(item => item.dictLabel)];
					this.fastDetectionProjectData = res.data;
					console.log('胶体金免疫层析法检测项目picker数据:', this.fastDetectionProjectColumns);
				}
			});
		},
		// 快速检测项目选择
		fastDetectionProjectConfirm(e) {
			const selectedLabel = e.value[0];
			// 根据选中的标签找到对应的值
			const selectedItem = this.fastDetectionProjectData.find(item => item.dictLabel === selectedLabel);
			if (selectedItem) {
				// 如果是样品明细中的检测项目选择
				if (this.currentSampleIndex !== null && this.currentSampleIndex !== undefined) {
					this.form.sylFastSampleInfoList[this.currentSampleIndex].detectionProject = selectedItem.dictValue;
				} else {
					// 如果是基本信息中的检测项目选择
					this.form.fastDetectionProject = selectedItem.dictValue;
				}
			}
			this.showFastDetectionProjectPicker = false;
		},
		// 根据值获取快速检测项目的标签
		getFastDetectionProjectLabel(value) {
			const item = this.fastDetectionProjectData.find(item => item.dictValue === value);
			return item ? item.dictLabel : value;
		},
		// 树种选择
		speciesConfirm(e) {
			const selectedLabel = e.value[0];
			// 根据选中的标签找到对应的值
			const selectedItem = this.getFilteredSpeciesOptions().find(item => item.treeSpeciesName === selectedLabel);
			if (selectedItem && this.currentSampleIndex !== undefined) {
				this.form.sylFastSampleInfoList[this.currentSampleIndex].product = selectedItem.treeSpeciesName;
				this.form.sylFastSampleInfoList[this.currentSampleIndex].productId = selectedItem.id;
			}
			this.showSpeciesPicker = false;
		},
		// 添加样品
		handleAddSample() {
			const newSample = {
				product: "",
				productId: "",
				detectionProject: "",
				cardinalNumber: "",
				source: "",
				sampleImgUrl: "",
				laboratoryCode: "",
				sampleImgRemark: "",
				qualified: null
			};
			this.form.sylFastSampleInfoList.push(newSample);
		},
		// 删除样品
		handleDeleteSample(index) {
			uni.showModal({
				title: '确认删除',
				content: '确定要删除这个样品吗？',
				success: (res) => {
					if (res.confirm) {
						this.form.sylFastSampleInfoList.splice(index, 1);
					}
				}
			});
		},
		// 处理树种选择器
		handleSpeciesPicker(index) {
			if (!this.form.orchardId) {
				uni.showToast({
					title: '请先选择园区',
					icon: 'none'
				});
				return;
			}
			
			const filteredSpecies = this.getFilteredSpeciesOptions();
			if (filteredSpecies.length === 0) {
				uni.showToast({
					title: '该园区暂无可用树种',
					icon: 'none'
				});
				return;
			}
			
			// 更新树种选择器数据
			this.speciesColumns = [filteredSpecies.map(item => item.treeSpeciesName)];
			this.currentSampleIndex = index;
			this.showSpeciesPicker = true;
		},
		// 处理检测项目选择器
		handleFastDetectionProjectPicker(index) {
			if (!this.form.fastDetectionAccording) {
				uni.showToast({
					title: '请先选择检测依据',
					icon: 'none'
				});
				return;
			}
			
			// 更新检测项目选项
			this.updateFastDetectionProjectOptions();
			// 如果没有传入index，说明是基本信息中的选择
			this.currentSampleIndex = index !== undefined ? index : null;
			this.showFastDetectionProjectPicker = true;
		},
		
		// 处理是否合格选择器
		handleQualifiedPicker(index) {
			// 如果是抽样单，不允许修改是否合格
			if (this.taskType === 'sampling') {
				uni.showToast({
					title: '抽样单阶段不能修改是否合格',
					icon: 'none'
				});
				return;
			}
			
			this.currentSampleIndex = index;
			this.showQualifiedPicker = true;
		},
		
		// 是否合格选择确认
		qualifiedConfirm(e) {
			const selectedValue = e.value[0];
			if (this.currentSampleIndex !== undefined) {
				this.form.sylFastSampleInfoList[this.currentSampleIndex].qualified = selectedValue === '合格';
			}
			this.showQualifiedPicker = false;
		},
		
		// 提交抽样信息
		submitSampleInfo() {
			// 验证必填字段
			if (!this.validateSampleInfo()) {
				return;
			}
			
			// 准备提交数据
			const submitData = this.form.sylFastSampleInfoList.map(sample => ({
				id: sample.id, // 抽样ID
				laboratoryCode: sample.laboratoryCode, // 实验室编码
				sampleImgUrl: sample.sampleImgUrl, // 抽样单图片
				detectionImgUrl: sample.detectionImgUrl || '', // 检测单图片
				sampleImgRemark: sample.sampleImgRemark, // 抽样单描述
				detectionImgRemark: sample.detectionImgRemark || '', // 检测单描述
				status: sample.qualified === true ? 1 : sample.qualified === false ? 2 : 0 // 是否合格 0未检验 1合格 2不合格
			}));
			
			console.log('提交抽样信息数据:', submitData);
			
			uni.showLoading({
				title: '提交中...'
			});
			
			batchUpdateSampleInfo(submitData).then(res => {
				uni.hideLoading();
				console.log('提交结果:', res);
				if (res.code === 200) {
					uni.showToast({
						title: '提交成功',
						icon: 'success'
					});
					// 延迟返回上一页
					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				} else {
					uni.showToast({
						title: res.msg || '提交失败',
						icon: 'none'
					});
				}
			}).catch(err => {
				uni.hideLoading();
				console.error('提交失败:', err);
				uni.showToast({
					title: '提交失败，请重试',
					icon: 'none'
				});
			});
		},
		
		// 验证抽样信息
		validateSampleInfo() {
			// 只有从待办任务跳转时才验证这些字段
			if (!this.isFromTask) {
				return true;
			}
			
			for (let i = 0; i < this.form.sylFastSampleInfoList.length; i++) {
				const sample = this.form.sylFastSampleInfoList[i];
				
			}
			
			return true;
		},
		// 根据园区mainProduct过滤树种选项
		getFilteredSpeciesOptions() {
			if (!this.form.orchardId) {
				return [];
			}
			
			// 找到选中的园区
			const selectedOrchard = this.inspectorData.find(orchard => orchard.id === this.form.orchardId);
			if (!selectedOrchard || !selectedOrchard.mainProduct) {
				return [];
			}
			
			// 将mainProduct按逗号分割成树种ID数组
			const mainProductIds = selectedOrchard.mainProduct.split(',').map(id => id.trim());
			
			// 根据园区的mainProduct（多个树种ID）过滤树种
			return this.speciesData.filter(species => {
				return mainProductIds.includes(species.id.toString());
			});
		},
		// 表单验证
		validateForm() {
			// 基本信息验证
			if (!this.form.detectionYear) {
				uni.showToast({
					title: '请选择年份',
					icon: 'none'
				});
				return false;
			}
			if (!this.form.fastDetectionType) {
				uni.showToast({
					title: '请选择快检检测类别',
					icon: 'none'
				});
				return false;
			}
			if (!this.form.fastDetectionAccording) {
				uni.showToast({
					title: '请选择快检检测依据',
					icon: 'none'
				});
				return false;
			}
			if (!this.form.institutionId) {
				uni.showToast({
					title: '请选择检测机构',
					icon: 'none'
				});
				return false;
			}
			if (!this.form.orchardId) {
				uni.showToast({
					title: '请选择园区',
					icon: 'none'
				});
				return false;
			}
			if (!this.form.fastDetectionProject) {
				uni.showToast({
					title: '请选择快速检测项目',
					icon: 'none'
				});
				return false;
			}
			
			// 样品明细验证
			if (!this.form.sylFastSampleInfoList || this.form.sylFastSampleInfoList.length === 0) {
				uni.showToast({
					title: '请至少添加一个样品',
					icon: 'none'
				});
				return false;
			}
			
			// 验证每个样品
			for (let i = 0; i < this.form.sylFastSampleInfoList.length; i++) {
				const sample = this.form.sylFastSampleInfoList[i];
				if (!sample.product) {
					uni.showToast({
						title: `第${i + 1}号样品请选择产品名称`,
						icon: 'none'
					});
					return false;
				}
				if (!sample.detectionProject) {
					uni.showToast({
						title: `第${i + 1}号样品请选择检测项目`,
						icon: 'none'
					});
					return false;
				}
				if (!sample.cardinalNumber) {
					uni.showToast({
						title: `第${i + 1}号样品请填写样品基数`,
						icon: 'none'
					});
					return false;
				}
				if (!sample.source) {
					uni.showToast({
						title: `第${i + 1}号样品请填写样品来源`,
						icon: 'none'
					});
					return false;
				}
			}
			
			return true;
		},
		// 提交任务（status: 2）
		submitTask() {
			if (!this.validateForm()) {
				return;
			}
			
			this.submitForm(2, '提交中...', '提交成功');
		},
		
		// 保存草稿（status: 1）
		submitDraft() {
			// 草稿不需要完整验证，只验证必填的基本信息
			if (!this.form.detectionYear) {
				uni.showToast({
					title: '请选择年份',
					icon: 'none'
				});
				return;
			}
			
			this.submitForm(1, '保存中...', '草稿保存成功');
		},
		
		// 重置表单
		resetForm() {
			uni.showModal({
				title: '确认重置',
				content: '确定要重置表单吗？所有数据将被清空。',
				success: (res) => {
					if (res.confirm) {
						// 重置表单数据
						this.form = {
							attachmentLink: null,
							createBy: null,
							createDeptId: null,
							createDeptName: null,
							createName: null,
							createTime: null,
							detectionYear: "",
							executionAgency: null,
							fastDetectionAccording: "",
							fastDetectionProject: "",
							fastDetectionType: "",
							id: null,
							instanceId: null,
							institutionId: null,
							institutionName: "",
							orchardId: null,
							orchardName: null,
							status: "2",
							sylFastSampleInfoList: [{ 
								product: "", 
								productId: null, 
								detectionProject: "", 
								cardinalNumber: "", 
								source: "", 
								sampleImgUrl: "",
								laboratoryCode: "",
								sampleImgRemark: "",
								qualified: null
							}],
							updateTime: null,
							userId: null
						};
						
						uni.showToast({
							title: '表单已重置',
							icon: 'success'
						});
					}
				}
			});
		},
		
		// 通用提交方法
		submitForm(status, loadingText, successText) {
			// 准备提交数据
			const submitData = {
				...this.form,
				status: status.toString(), // 设置状态：1-草稿，2-提交
				// 确保园区名称正确设置
				orchardName: this.form.orchardName || this.getInspectorLabel(this.form.orchardId),
				// 确保检测机构名称正确设置
				institutionName: this.form.institutionName || this.getInstitutionLabel(this.form.institutionId)
			};
			
			console.log('提交数据:', submitData);
			
			uni.showLoading({
				title: loadingText
			});
			
			addFastDetectionTask(submitData).then(res => {
				uni.hideLoading();
				console.log('提交结果:', res);
				if (res.code === 200) {
					uni.showToast({
						title: successText,
						icon: 'success'
					});
					// 延迟返回上一页
					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				} else {
					uni.showToast({
						title: res.msg || '操作失败',
						icon: 'none'
					});
				}
			}).catch(err => {
				uni.hideLoading();
				console.error('操作失败:', err);
				uni.showToast({
					title: '操作失败，请重试',
					icon: 'none'
				});
			});
		},
	},
	computed: {
		navbarHeight() {
			// 如果设置了自定义高度，则使用自定义高度
			if (this.customNavbarHeight) {
				return this.customNavbarHeight;
			}
			// 否则自动计算：状态栏高度 + 导航栏高度
			const systemInfo = uni.getSystemInfoSync();
			// 将px转换为rpx (1px = 2rpx)
			const statusBarHeightRpx = systemInfo.statusBarHeight * 2;
			const navbarHeightRpx = 44 * 2; // 44px = 88rpx
			return statusBarHeightRpx + navbarHeightRpx;
		},
	},
}
</script>

<style lang="scss" scoped>
.mine-navbar-bg {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	z-index: 1;
}

// 样品明细样式
.sample-card {
	border: 2rpx solid #e4e7ed;
	border-radius: 8rpx;
	background: #fff;
	margin-bottom: 20rpx;
}

.sample-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 32rpx;
	background: #f5f7fa;
	border-bottom: 2rpx solid #e4e7ed;
}

.sample-content {
	padding: 20rpx 32rpx;
}

.add-sample-btn {
	text-align: center;
	padding: 20rpx 0;
}

.col-green {
	color: #67C23A;
}

.col-red {
	color: #f56c6c;
}

.disabled {
	opacity: 0.5;
	pointer-events: none;
}
</style>
